import requests
import json
import execjs
import csv
import time
import random

cookies = {
    "ibulanguage": "CN",
    "ibulocale": "zh_cn",
    "cookiePricesDisplayed": "CNY",
    "UBT_VID": "1733365254563.a589R82d4F5X",
    "MKT_CKID": "1733365254517.40qbh.3mqo",
    "GUID": "09031105311803569409",
    "_RF1": "61.136.204.101",
    "_RSG": "wVqX3sW0kG7hhUmKiJ8viB",
    "_RDG": "281b6eb7d877422ddf2b45c18c0d2624cc",
    "_RGUID": "742e020d-8387-47fa-bb39-213b14c1eaeb",
    "nfes_isSupportWebP": "1",
    "_ga": "GA1.1.2004157457.1733384709",
    "MKT_Pagesource": "PC",
    "Hm_lvt_a8d6737197d542432f4ff4abc6e06384": "1733462559,1733463633,1733474837,1733493757",
    "HMACCOUNT": "A8906F95E8CCD35D",
    "librauuid": "",
    "cticket": "B4464CCB0A51EAD2BA9FEFFAA7CC8D6EAF5508EEEA87A6BD638D9AE0B7E4585A",
    "login_type": "0",
    "login_uid": "9BAFD8B097119F4CD60CA37221651924",
    "DUID": "u=0108E0C9C58E811798122CEDCEA14404&v=0",
    "IsNonUser": "F",
    "AHeadUserInfo": "VipGrade=0&VipGradeName=%C6%D5%CD%A8%BB%E1%D4%B1&UserName=&NoReadMessageCount=0",
    "Hm_lpvt_a8d6737197d542432f4ff4abc6e06384": "1733494147",
    "_ga_5DVRDQD429": "GS1.1.1733493757.4.1.1733494150.0.0.0",
    "_ga_B77BES1Z8Z": "GS1.1.1733493757.4.1.1733494150.29.0.0",
    "_ga_9BZF483VNQ": "GS1.1.1733493757.4.1.1733494150.0.0.0",
    "intl_ht1": "h4=2_433981,2_48565681,986_3363875,37_449677,95_689713",
    "_jzqco": "%7C%7C%7C%7C1733458549461%7C1.934577289.1733365254520.1733494168135.1733494203488.1733494168135.1733494203488.0.0.0.60.60",
    "_bfa": "1.1733365254563.a589R82d4F5X.1.1733494168084.1733494203928.11.11.102003"
}

id_list =  [
    433981
]
headers = {
            "accept": "application/json",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://hotels.ctrip.com",
            "p": "79801998951",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://hotels.ctrip.com/",
            "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
        }

with open('价格4.csv', 'a', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    writer.writerow(['酒店ID','房间名称','价格'])
    for id in id_list:
        print('酒店ID：',id)
        # response = requests.get(
        #     'https://share.proxy.qg.net/get?key=C2695231&num=1&area=&isp=0&format=json&distinct=false')
        # print(response.json())
        # print(response.json()['data'][0]['server'])
        # targetURL = "https://test.ipw.cn"
        # proxyAddr = response.json()['data'][0]['server']
        # authKey = "C2695231"
        # password = "C9928A3124C7"
        # # 账密模式
        # proxyUrl = "http://%(user)s:%(password)s@%(server)s" % {
        #     "user": authKey,
        #     "password": password,
        #     "server": proxyAddr,
        # }
        # proxies = {
        #     "http": proxyUrl,
        #     "https": proxyUrl,
        # }

        url = "https://m.ctrip.com/restapi/soa2/21881/json/getHotelScript"
        data = {
            "callback": "fzrNRYaBwZ",
            "a": id,
            "d": "zh-cn",
            "e": 2,
            "head": {
                "Locale": "zh-CN",
                "Currency": "CNY",
                "Device": "PC",
                "UserIP": "61.136.204.101",
                "Group": "ctrip",
                "ReferenceID": "",
                "UserRegion": "CN",
                "AID": None,
                "SID": None,
                "Ticket": "",
                "UID": "",
                "IsQuickBooking": "",
                "ClientID": "09031105311803569409",
                "OUID": None,
                "TimeZone": "8",
                "P": "79801998951",
                "PageID": "102003",
                "Version": "",
                "HotelExtension": {
                    "WebpSupport": True,
                    "group": "CTRIP",
                    "Qid": None,
                    "hasAidInUrl": False
                },
                "Frontend": {
                    "vid": "1733365254563.a589R82d4F5X",
                    "sessionID": "2",
                    "pvid": "1"
                }
            },
            "ServerData": ""
        }
        data = json.dumps(data, separators=(',', ':'))
        response = requests.post(url, headers=headers, cookies=cookies, data=data,)
        Response=response.json()['Response']
        code=Response.split('window')[1][1:].replace(');})();','')
        # code = json.dumps(code)
        print(code)
        with open('酒店testab.js', 'r', encoding='utf8') as f:
            demo = f.read().replace("'data'",code)
        # print(demo)
        testab =execjs.compile(demo).call('testab',code)
        print(testab)
        headers = {
            "accept": "application/json",
            "accept-language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "content-type": "application/json;charset=UTF-8",
            "origin": "https://hotels.ctrip.com",
            "p": "79801998951",
            "pragma": "no-cache",
            "priority": "u=1, i",
            "referer": "https://hotels.ctrip.com/",
            "sec-ch-ua": "\"Google Chrome\";v=\"131\", \"Chromium\";v=\"131\", \"Not_A Brand\";v=\"24\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
        }

        url = "https://m.ctrip.com/restapi/soa2/21881/json/rateplan"
        params = {
            "testab": testab
        }
        data = {
            "checkIn": "2024-12-05",
            "checkOut": "2024-12-06",
            "adult": 1,
            "popularFacilityType": "",
            "child": 0,
            "roomNum": 1,
            "masterHotelId": id,
            "age": "",
            "hotel": "689713",
            "filterData": [],
            "guestCountFilterType": 1,
            "genk": True,
            "genKeyParam": {
                "a": 689713,
                "b": "2024-12-05",
                "c": "2024-12-06",
                "d": "zh-cn",
                "e": 2
            },
            "pageTraceId": "4691920a-17ee-420f-b0e7-1f6dbdec277c",
            "head": {
                "Locale": "zh-CN",
                "Currency": "CNY",
                "Device": "PC",
                "UserIP": "61.136.204.101",
                "Group": "ctrip",
                "ReferenceID": "",
                "UserRegion": "CN",
                "AID": None,
                "SID": None,
                "Ticket": "",
                "UID": "",
                "IsQuickBooking": "",
                "ClientID": "09031105311803569409",
                "OUID": None,
                "TimeZone": "8",
                "P": "79801998951",
                "PageID": "102003",
                "Version": "",
                "HotelExtension": {
                    "WebpSupport": True,
                    "group": "CTRIP",
                    "Qid": None,
                    "hasAidInUrl": False,
                    "hotelUuidKey": "SnDW3hxTtjsFRpcKkPelkEp7WPvL5EmTY5YgzehnEsPyT9Y6mEpdYtOKOJtYT5Rgmy15ROLeD6EcdjQHW3BIU3jQMKAYpEGQxshrG0yHTi0Gr19K3J0mxgLwGNRbzjdJ86ehOw6GIqSjzJoTvm0YFDyhfjN5vzpe1FYDqjapy0sYG9e1UjSYqvNOr3OEaFyoBjU0vklEXcvmzW5GjntJ4LJBNEUYUoyc0xTQrh4YFtiotw43RmNENzWg1jhSwTSiUY94yc1JX3Rfbxobr46xoYaPxfUeTZwc5YQnjhMWaYF7xflIQ8wSOvhUYgLyksjOnvDHet9YLUjdPy1JBqvgTYmTycmjglvLOeogY3kj7byoJOMYLkvtsWA9WAgR9HRABv0YBvZ1xOlYszvoMeahYPNigMYmhxttxDZifY8ZWGJ3Se0yHGIQ7rZYBbrzORD5itzi8tK7Oe4YFaKGNyc4vhsYqlihGiF6iGPjQDrOSx4Tw6YzPI4bycNx5GYz5EaOYcow8gjcly63YZ6wksiT7YX5wcYhXYf9yHqx0XRUgyNqikdiN9iqNyhMWPfifbjlPW9tRH9i51WqoyDnIpmvoYXZjqARsdwATv4tytsJBY4gYkmWcE3PRpLyBsi7fiM4iLFwglJLgYbsJanEmBJABw9ai1dyANiN3x7YFkecfKAFr6oj3Hw6dv3oj8NwkFi8SEQYq7W9pimly4PRDav0QYbXWaZeNARFXWaLj8kWpSiDDx5TY1YzyDqeB5yGARNUvM3YAOWhFeh6RzfW7DEDLWGFE4Pe3fxBY3cJoMRO8Y6kR5nyXcipHi16iMDycQWf7iaqjzMWHSRZ4Yz9vt6WFTim1wUYHqwh6J8hRNpE7pj87WgcWHfWalYOmYlNY1sRBMYhmWZ1YLaY09YdHjADet0EAQWdke9BwUOecgj5GYmOynbE6OjzpE1BrUnjFkwcSyScrPor99x8Y4PRf1WBTWpfWsnWN5Y8Y5j0dwdgyQavPmE3bW5pyTtjAJzcvhFENPW0gyMojfnvpMRZNITY94wQDImoeZkEMmE3QEnSRO0EaXEkhxNzydYMpKP5K8nEUQYMPEdcELGY7qYFBYX6YQhRqfw4L"
                },
                "Frontend": {
                    "vid": "1733365254563.a589R82d4F5X",
                    "sessionID": "2",
                    "pvid": "1"
                }
            },
            "ServerData": ""
        }
        data = json.dumps(data, separators=(',', ':'))
        response = requests.post(url, headers=headers, cookies=cookies, params=params, data=data,)
        print(response.json())
        datas = response.json()['Response']['baseRooms']
        for rooms in datas:
            price = rooms['saleRoom'][0]['money']['price']
            roomName = rooms['baseRoom']['roomName']
            writer.writerow([str(id), roomName, price])
            print(id, roomName, price)
        time.sleep(random.uniform(1, 3))


